﻿using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using System;
using System.Text;
using System.Windows;

namespace CheckTicket.Sample
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private readonly MainViewModel _mainViewModel;

        /// <summary>
        ///
        /// </summary>
        public MainWindow()
        {
            InitializeComponent();
            _mainViewModel = new MainViewModel();
            //_httpListener = new HttpListener();
            DataContext = _mainViewModel;
            CommonSetting.TicketType = _mainViewModel.TicketTypes[0];
        }

        private IWebHost _host;

        private static IWebHostBuilder CreateHostBuilder(int port, string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseKestrel(options =>
                {
                    options.ListenAnyIP(port);
                })
                .UseStartup<Startup>();

        //private HttpListener _httpListener;

        private void BtnStart_OnClick(object sender, RoutedEventArgs e)
        {
            //_httpListener.Prefixes.Add("http://*:8000/"); //添加需要监听的url范围
            //while (true)
            //{
            //    _httpListener.Start(); //开始监听端口，接收客户端请求
            //    //阻塞主函数至接收到一个客户端请求为止
            //    HttpListenerContext context = _httpListener.GetContext();
            //    HttpListenerRequest request = context.Request;
            //    HttpListenerResponse response = context.Response;
            //    byte[] buffer = System.Text.Encoding.UTF8.GetBytes("responseString");

            //    System.IO.Stream output = response.OutputStream;
            //    output.Write(buffer, 0, buffer.Length);
            //    //关闭输出流，释放相应资源
            //    output.Close();
            //    _httpListener.Stop(); //关闭HttpListener
            //}

            _host = CreateHostBuilder(_mainViewModel.Port, null).Build();
            //host.Start();
            _host.RunAsync();
            BtnStart.IsEnabled = false;
            BtnStop.IsEnabled = true;
            TxtStatus.Text = "启动监听成功！";
            TxtStatusMsg.Visibility = Visibility.Visible;
            TxtPort.IsEnabled = false;
        }

        private void BtnStop_OnClick(object sender, RoutedEventArgs e)
        {
            if (_host != null)
            {
                _host.StopAsync();
                //host.WaitForShutdown();
                _host.Dispose();
                _host = null;
            }
            BtnStart.IsEnabled = true;
            BtnStop.IsEnabled = false;
            TxtStatus.Text = "停止监听成功！";
            TxtPort.IsEnabled = true;
        }

        private void MainWindow_OnLoaded(object sender, RoutedEventArgs e)
        {
            BtnStart.IsEnabled = true;
            BtnStop.IsEnabled = false;
            TxtStatusMsg.Visibility = Visibility.Collapsed;
            MessageBus.Instance.Received += Instance_Received;
        }

        private void Instance_Received(string message)
        {
            this.Dispatcher.Invoke(() =>
            {
                _mainViewModel.Message.Add($"{DateTime.Now:yyyMMdd HH:mm:ss:fff}：{message}");
            });

            //throw new System.NotImplementedException();
        }

        private void MenuItem_OnClick(object sender, RoutedEventArgs e)
        {
            LbMsg.SelectAll();
        }

        private void Copy_OnClick(object sender, RoutedEventArgs e)
        {
            if (LbMsg.SelectedItems.Count > 0)
            {
                StringBuilder stringBuilder = new StringBuilder();

                foreach (var lbMsgSelectedItem in LbMsg.SelectedItems)
                {
                    stringBuilder.AppendLine(lbMsgSelectedItem.ToString());
                }
                Clipboard.SetDataObject(stringBuilder.ToString());
            }
        }
    }
}